package com.ruoyi.common.utils;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 错误信息处理类。
 *
 * @author ruoyi
 */
public class ExceptionUtil extends cn.hutool.core.exceptions.ExceptionUtil {
    /**
     * 获取exception的详细错误信息。
     */
    public static String getExceptionMessage(Throwable e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        return sw.toString();
    }

    public static String getRootErrorMessage(Exception e) {
        Throwable root = ExceptionUtils.getRootCause(e);
        root = (root == null ? e : root);
        if (root == null) {
            return "";
        }
        String msg = root.getMessage();
        if (msg == null) {
            return "null";
        }
        return StrUtil.nullToDefault(msg, "");
    }

    public static synchronized String getPrintFirstLineException(Throwable e) {
        return getPrintException(e, 1);
    }

    public static synchronized String getPrintFiveLineException(Throwable e) {
        return getPrintException(e, 5);
    }

    public static synchronized String getPrintException(Throwable e, Integer line) {
        StringBuilder msg = new StringBuilder(e.toString() + "\n");

        StackTraceElement[] stackTraceElementArray = e.getStackTrace();
        int maxLine = stackTraceElementArray.length;
        line = Math.min(line, maxLine);

        for (int i = 0; i < line; i++) {
            StackTraceElement stackTraceElement = stackTraceElementArray[i];
            String fileName = stackTraceElement.getFileName();
            String className = stackTraceElement.getClassName();
            String methodName = stackTraceElement.getMethodName();
            int lineNumber = stackTraceElement.getLineNumber();

            msg.append("\tat ").append(className).append(".").append(methodName).append("(").append(fileName)
                    .append(":").append(lineNumber).append(")\n");
        }
        msg.append("......");
        return msg.toString();
    }
}
